<template>
  <div class="yxp-course">
    <div class="yxp-composition-top">
      <div class="back" @click="handleBack">
        <span></span>
      </div>
      <div class="yxp-top-c">文字表达训练</div>
      <div class="yxp-top-r">
        <span class="right-text-item" v-for="(item,i) in modelArr"  :key="'n' + i" @click="handleChangeModel(i)">{{item}}</span>
      </div>
    </div>
    <div class="yxp-scene-main" >
      <div class="main-box">
        <div  style="margin-right: 20px;" class="main-box-content">
          <div class="content">
            <div class="content-wrap upload-box">
              <h3 class="work-title">【写作要求】</h3>
              <div class="work-info" v-html="content.require" v-if="workIndex === 0"></div>
              <div class="work-info" v-html="imitation_require" v-if="workIndex === 1"></div>
            </div>
          </div>
        </div>
        <div class="main-box-content" >
          <div class="content">
            <div class="content-wrap  upload-wrap">
              <div class="upload-pic">
                <div class="upload" id="yxp-upload-index" @click="handleCode">
                  <img src="@/assets/composition/upload-icon.png" class="upload-icon"/>
                  <p class="tips">上传手写作文</p>
                </div>
              </div>
              <div class="foot-content">
                <div class="class-box">
                    <div class="class-box-l">课后作业：</div>
                    <div class="class-box-r">
                        <div class="class-box-r-item" :class="{checked: workIndex === i}" v-for="(item,i) in workArr" :key="i"  @click="handleChangeWork(i)">
                          <div class="dot"><span></span></div>{{item}}
                        </div>
                    </div>
                </div>
                <div class="btn" id="yxp-upload-end" @click="handleEnd">结束训练</div>
                </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="mark" v-if="isShow || isPoint || isModel" @click="isShow = false"></div>
    <readPop :isPoint="isPoint" :content="content.analysis" @point="handlePoint" />
    <model :isModel="isModel" :enHead="enHead" :enEnd="enEnd" :articleType="articleType" :enWord="enText" @model="handleModel" />
    <BackTips title="是否退出学习？" :isBack="isBack"  :courseId="toNumber(userid)"  type="1" @close="handleClosed"/>
    <div class="yxp-upload-code" v-if="isShow">
      <img src="@/assets/composition/upload-close.png" class="close" id="yxp-upload-close" @click="no" />
      <div class="code">
        <img :src="codePath" />
      </div>
    </div>
  </div>
</template>
<script>
import readPop from '@/views/components/readPop.vue'
import model from '@/views/components/model.vue'
import BackTips from '@/views/components/BackTips.vue'
import {storage} from '@/utils/storage.js'
import {toNumber} from "lodash/lang";
import {createQrcode, progressSet, writingImg, writingImgUp, writingMode} from "@/api/reverse";
// import { createQrcode, getChropath, subEssay } from '@/services/composition.js'
export default {
  name: 'uploadIndex',
  components: {
    model,
    readPop,
    BackTips
  },
  data () {
    return {
      title: '英语习得与切片训练',
      modelArr: ['要点解读','查看模型'],
      workArr: ['重复训练','仿写训练'],
      workIndex: 0,
      model: 0,
      id: 0,
      courseId: '',
      codePath: '',
      imitation_require: '',
      userid: 0,
      course_type: 0,
      content: '',
      enText: [],
      enHead: '',
      result: '',
      enEnd: '',
      ModeInfo: '',
      iNow: -1,
      intervalId: '',
      iStep: -1,
      isShow: false,
      isBack: false,
      isOpen: false,
      isNext: false,
      isPoint: false,
      isModel: false,
      popTitle: '开始全文还原训练吧~',
      isEn: false,
      articleType: 0,
      packageId: 0,
      num: 0,
    }
  },
 async created () {
    if (this.$route.query.userid) {
      let { userid, courseId, course_type } = this.$route.query
      this.id = +userid
      this.userid = this.$route.query.userid
      this.courseId = +courseId
      this.course_type = +course_type
      let pms ={
        id:this.$route.query.id,
        userId:this.$route.query.userid,
        progress:5,
        state:1,
      }
      await progressSet(pms).then((res)=>{
        let ModeListInfo = res.data;
        storage.set('ModeListInfo', ModeListInfo)
      })
    }
    this.ModeInfo = storage.get("ModeListInfo");

    let data = storage.get('sceneData')
    let pas ={
      unit:data.unit,
      courseId:data.courseId,
      mode:3,
    }
    writingMode(pas).then((res)=>{
      this.imitation_require = res.data.require
    })
    if (data) {
      this.content = data
      this.articleType = data.type
      let enText = data.sentence
      let enArr = []
      enText.map(item =>{
        let obj = {}
        let val = ''
        if (item.indexOf('&&') !== -1 && item.indexOf('##') !== -1) {
          let val1 = item.replace('&&', '')
          console.log(val1)
          val = val1.replace('##','<br>')
          obj.word = val
          obj.isStart = 0
          enArr.push(obj)
        } else if (item.indexOf('&&') !== -1) {
          val = item.replace('&&', '')
          obj.word = val
          obj.isStart = 0
          enArr.push(obj)
        } else if (item.indexOf('##') !== -1) {
          val = item.replace('##','<br>')
          obj.word = val
          obj.isStart = 1
          enArr.push(obj)
        } else {
          val = item
          obj.word = val
          obj.isStart = 2
          enArr.push(obj)
        }
      })
      this.enText = enArr
    }
  },
  methods: {
    toNumber,
    handleChangeModel (i) {
      this.model = i
      if (i === 0) {
        this.isPoint = true
      } else {
        this.isModel = true
      }
    },
    handleCode () {
      this.getCode();

    },
    no(){
      this.isShow = false;
      this.stopRequest()
    },
   async handleEnd () {
     this.$router.push({
       path: '/composition/uploadResult',
         query: {
           userId: this.userid,
           courseId: this.ModeInfo.courseId,
           packageId:this.ModeInfo.packageId,
           num: this.ModeInfo.num,
         }
     })
     // this.$router.push({
     //   path: '/composition/uploadResult',
     //   query: {
     //     query: {
     //       userId: this.userid,
     //       courseId: item.courseId,
     //       packageId: item.id,
     //       num: item.num,
     //     }
     //   }
     // })
      // if (this.result){
      //
      // }else {
      //   this.$message.error('请上传作业');
      // }
      // this.$router.push({
      //     path: '/composition/uploadResult',
      //     query: {
      //       userid:this.userid
      //     }
      //   })
      // this.getPic()
    },
    //获取tup
    // async getPic () {
    //   let data = await getChropath({ essay_id: this.id })
    //     if (data.code === 1) {
    //       if (data.data.path === '') {
    //         //this.$toast('未上传作文图片，请确认手机端是否上传成功')
    //         //return
    //       }
    //       this.endCourse(data.data.path)
    //     }
    // },
    //结束学习
    async endCourse (path) {
      // let params = {
      //   essay_id: +this.id,
      //   curr_id: +this.courseId,
      //   type: this.workIndex.toString(),
      //   path: path
      // }
      let data = await subEssay(params)
      if (data.code === 1) {
        this.$router.push({
          path: 'uploadResult',
          query: {
            id: data.data,
            courseId: this.courseId,
            course_type: this.course_type,
            modal: 0
          }
        })
      }
    },
    // 获取二维码
    async getCode () {
      let params ={
        userId:this.userid,
        courseId:this.ModeInfo.courseId,
        packageId:this.ModeInfo.packageId,
        num:this.ModeInfo.num
      }
      // console.log(params)
     await createQrcode(params).then((res)=>{
       this.codePath = res.data
       this.isShow = true
     });
     if (this.result){
       let query= {
         id: this.userid,
         courseId:this.ModeInfo.courseId,
         packageId:this.ModeInfo.packageId,
         imgurl:this.result?this.result:'',
         num:this.ModeInfo.num,
       }
       await writingImg(query).then((res)=>{
         this.$message.success(res.message);
       })
     }
      //开始监听图片上传请求
      this.startRequest()
    },
    async fetchData() {
      this.loading = true;
      this.error = null;
      try {
        let data = {
          userId: this.userid,
          courseId: this.ModeInfo.courseId,
          packageId: this.ModeInfo.packageId,
          num: this.ModeInfo.num
        }
        const response = await writingImgUp(data);  // 替换为你的接口地址
        if (response.data.imageurl) {
          this.result = response.data.imageurl;  // 接口返回的内容
          this.isShow = false;
          this.stopRequest();           // 有值时停止请求
        } else {
          console.log('接口返回空值，继续请求...');
        }
      } catch (err) {
        // this.$message.error(err.message);  // 请求失败时显示错误信息
      } finally {
        // this.loading = false;
      }
    },
    // 启动请求的定时器
    startRequest() {
      this.intervalId = setInterval(this.fetchData, 1000);  // 每1秒请求一次
    },
    // 停止请求
    stopRequest() {
      if (this.intervalId) {
        clearInterval(this.intervalId);  // 清除定时器
        this.intervalId = null;
      }
    },
    // 切换work
    handleChangeWork (i) {
      this.workIndex = i
    },
    handlePoint (val) {
      this.isPoint = val
    },
    handleModel (val) {
      this.isModel = val
    },
    handleBack () {
      this.isBack = true
    },
    handleClosed (val) {
      this.isBack = val
    }
  }
}
</script>
<style  scoped>
.mark{
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, .5);
  z-index: 150;
}
.dot{
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 1px solid #999;
  border-radius: 12px;
  margin-right: 10px;
  vertical-align: middle;
  cursor: pointer;
}
.content{
  padding: 20px;
  height: 100%;
}
.class-box{
  display: flex;
  justify-content: center;
  align-items: center;
}
.work-title{
  font-size: 30px;
  font-weight: 700;
  color: #333;
  text-align: center;
}
.main-box-content{
  width: 520px;
  position: relative;
  background: #fff;
  height: 540px;
  overflow: hidden;
  overflow-y: auto;
  padding: 20px;
  border-radius: 10px;
}
/* 隐藏滚动条 */
::-webkit-scrollbar {
  display: none;
}
.yxp-course{
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow: hidden;
  background: #F0F2F4;
  height: 100%;
}
.main-box{
  position: relative;
  display: flex;
  justify-content: center;
  margin-top: 30px;
  width: inherit;
}
.yxp-composition-top {
  position: relative;
  display: flex;
  height: 80px;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-size: 20px;
  font-weight: 700;
  text-align: center;
  background: #fff;
  padding: 0 40px;
  .back{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 30px;
    height: 27px;
    span{
      display: block;
      width: 30px;
      height: 27px;
      background: url() no-repeat;
      background-size: 100%;
      cursor: pointer;
    }
  }
  .yxp-top-c{
    width: 100%;
    font-size: 20px;
    flex: 1;
    font-weight: 700;
  }
    .yxp-top-r {
      color: #27bfa3;
      font-size: 20px;
      font-weight: 400;
      .right-text-item {
        cursor: pointer;
        &:last-child {
          margin-left: 60px;
        }
      }
    }
  }
.upload-wrap {
  height: calc(100% - 153px) !important;
  padding: 0 !important;
}
  .upload-box {
    .work-title {
      padding-top:2px !important;
    }
  }
.foot-content {
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 100%;
  height: 165px;
  z-index: 10;
  .class-box {
    display: flex;
    justify-content: center;
    align-items: center;
    .class-box-l {
      font-size:20px;
      font-weight:bold;
      color:#333;
      margin-right: 10px;
    }
    .class-box-r-item{
      display: flex;
      font-size: 20px;
      align-items: center;
    }
    .class-box-r-item:first-child{
      margin-right: 20px;
    }
    .class-box-r {
      display: flex;
      align-items: center;
      .checked {
        color: #27BFA3;
        .dot {
          position: relative;
          border: 1px solid #27BFA3 !important;
          span {
            display: block;
            width: 12px;
            height: 12px;
            background: #27BFA3;
            border-radius: 6px;
            margin-left: 5px;
            margin-top: 5px;
          }
        }
      }
      .class-box-item {
        font-size:20px;
        font-weight:400;
        color: #999;

        .dot {
          display: inline-block;
          width: 24px;
          height: 24px;
          border: 1px solid #999;
          border-radius: 12px;
          margin-right: 10px;
          vertical-align: middle;
          cursor: pointer;
        }
      }
    }
  }
.btn {
  width: calc(100% - 40px);
  height: 70px;
  line-height:70px;
  text-align: center;
  font-size:24px;
  font-weight:400;
  color: #fff;
  background:linear-gradient(360deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
  box-shadow:0px 5px 10px rgba(59,201,164,0.3);
  background: #3BC9A4;
  border-radius: 10px;
  margin: 20px auto 0;
  cursor: pointer;
  &:hover {
    background: linear-gradient(180deg, #07E6AA 0%, #21D6B5 100%);
    box-shadow: 0px 3px 6px rgba(23, 178, 145, 0.4);
    }
  }
}
.upload-pic {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;

}
.upload {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  .upload-icon {
    display: block;
    width: 110px;
    height: 110px;
  }
  .tips {
    font-size:24px;
    font-weight:400;
    color: #2496EF;
    text-align: center;
    margin-top: -20px;
  }
}
  .yxp-upload-code {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    width: 500px;
    height: 633px;
    background: url(@/assets/composition/upload-code.png) no-repeat;
    background-size: 100% 100%;
    z-index: 1200;
    .close {
      position: absolute;
      right:20px;
      top: 123px;
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
    .code {
      width: 400px;
      height: 400px;
      border-radius: 20px;
      margin: 183px 50px 50px;
      img {
        width: 360px;
        height:360px;
        margin: 20px auto;
      }
    }
  }



</style>